package com.fenghuajueli.libbasecoreui.ui;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils;
import com.fenghuajueli.libbasecoreui.databinding.ActivityCustomerServiceBinding;
import com.fenghuajueli.libbasecoreui.dialog.CommonTipsDialog;
import com.fenghuajueli.libbasecoreui.mvp.BaseActivity;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.ijj.tookit.file.IFileUtils;
import com.ijj.tookit.file.IImageType;
import com.ll.permission.AllowPermissionUseCase;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 联系客服界面
 */
public class CustomerServiceActivity extends BaseActivity {

    public static void start(Context context) {
        Intent intent = new Intent(context, CustomerServiceActivity.class);
        context.startActivity(intent);
    }

    private ActivityCustomerServiceBinding binding;

    private String paramterValue = "";

    /**
     * 获取客服链接
     */
    public static String getUrl() {
        String url;
        String serverUrl = SwitchKeyUtils.getMQServerUrl();
        if (TextUtils.isEmpty(serverUrl)) {
            url = "https://www.bestkids.net/chatlink.html?eid=a589f0cc0aa1e64691c5dc7236279fa3&subSource=sub_source_2";
        } else {
            String userId = "";
            String vipCode = "";
            if (UserInfoUtils.getInstance().isLogin()) {
                userId = String.valueOf(UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getUser_id());
                vipCode = UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getShare_id();
            }
            url = serverUrl + "&metadata=" + "{\"name\":\"" + userId + "\",\"address\":\"" + vipCode + "\"}";
        }
        return url;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCustomerServiceBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        MyStatusBarUtils.setStatusBarWhite(this, "#007aff");

        String serverUrl = SwitchKeyUtils.getMQServerUrl();

        if (TextUtils.isEmpty(serverUrl)) {
//            binding.webView.setVisibility(View.GONE);
//            binding.tvServerQQ.setText("客服QQ：" + SwitchKeyUtils.getServiceQQ());
//            binding.tvServerDesc.setVisibility(View.VISIBLE);
//            binding.tvServerQQ.setVisibility(View.VISIBLE);
//            //设置客服qq相关信息
//            binding.tvServerQQ.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    ClipboardUtils.copyText(SwitchKeyUtils.getServiceQQ());
//                    ToastUtils.showShort("复制成功!");
//                }
//            });

            binding.webView.setVisibility(View.VISIBLE);
            binding.tvServerDesc.setVisibility(View.GONE);
            binding.tvServerQQ.setVisibility(View.GONE);
            paramterValue = "https://www.bestkids.net/chatlink.html?eid=a589f0cc0aa1e64691c5dc7236279fa3&subSource=sub_source_2";
            binding.webView.loadUrl(paramterValue);
        } else {
            binding.webView.setVisibility(View.VISIBLE);
            binding.tvServerDesc.setVisibility(View.GONE);
            binding.tvServerQQ.setVisibility(View.GONE);
            String userId = "";
            String vipCode = "";
            if (UserInfoUtils.getInstance().isLogin()) {
                userId = String.valueOf(UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getUser_id());
                vipCode = UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getShare_id();
            }
            paramterValue = "&metadata=" + "{\"name\":\"" + userId + "\",\"address\":\"" + vipCode + "\"}";

            binding.webView.loadUrl(serverUrl + paramterValue);
        }

        initWebViewClickListener();
    }


    @Override
    protected void onResume() {
        super.onResume();
        binding.webView.onResume();
    }

    @Override
    protected void onPause() {
        binding.webView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        binding.webView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        binding.webView.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onBackPressed() {
        if (!binding.webView.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }


    private void initWebViewClickListener() {
        // 处理下载文件的情况
        binding.webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                LogUtils.d("onDownloadStart: " + url + "--" + userAgent + "--" + contentDisposition + "--" + mimetype);
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });

        // 处理无法复制部分聊天内容和保存图片的问题
        binding.webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = binding.webView.getHitTestResult();
                if (result == null) {
                    return false;
                }
                int resultType = result.getType();
                String resultExtra = result.getExtra();

                if (resultType == WebView.HitTestResult.IMAGE_TYPE || resultType == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    // 下载并保存到相册
                    downloadAndSave(resultExtra);
                } else if (resultType == WebView.HitTestResult.SRC_ANCHOR_TYPE || resultType == WebView.HitTestResult.PHONE_TYPE || resultType == WebView.HitTestResult.EMAIL_TYPE) {
                    // 超链接、手机号、邮箱 自动复制
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData mClipData = ClipData.newPlainText("Label", resultExtra);
                    cm.setPrimaryClip(mClipData);
                    ToastUtils.showShort("复制成功");
                }
                return false;
            }
        });
    }

    private void downloadAndSave(final String picUrl) {
        if (!TextUtils.isEmpty(picUrl) && picUrl.startsWith("http")) {
            CommonTipsDialog commonTipsDialog = new CommonTipsDialog(this, "是否保存当前图片？", "取消", "保存");
            commonTipsDialog.setConfirmListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AllowPermissionUseCase.useGalleryImages(
                            CustomerServiceActivity.this,
                            "相册权限",
                            "用于图片上传功能，需要访问您的相册权限，如若拒绝，将无法使用上述功能。",
                            "相册权限：该功能需要相册权限才可以正常运行，用于上传反馈图片。",
                            "CustomerService",
                            "请先申请相册权限!",
                            () -> {
                                save(picUrl);
                                return null;
                            });
                }
            });
            commonTipsDialog.show();
        }
    }

    private void save(String picUrl) {
        new Thread(() -> {
            URL url;
            InputStream connectionIs = null;
            try {
                url = new URL(picUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {
                    connectionIs = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(connectionIs);
                    // 保存
                    IFileUtils.Companion.getInstance().saveBitmap2Gallery(bitmap, IImageType.PNG);
                    runOnUiThread(() -> ToastUtils.showShort("图片保存成功"));
                }
            } catch (Exception e) {
                if (!isDestroyed()) {
                    runOnUiThread(() -> ToastUtils.showShort("保存失败"));
                }
                e.printStackTrace();
            } finally {
                try {
                    if (connectionIs != null) {
                        connectionIs.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


}